from selenium import webdriver
import os
from time import sleep
# from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from django.http import JsonResponse
import re


def login_auto(usrname, password):
    file_path = os.path.abspath(__file__)
    base_path = os.path.dirname(os.path.dirname(file_path))
    drive_path = os.path.join(base_path, 'drive', 'msedgedriver')

    browser = webdriver.Edge(drive_path)
    browser.get('https://www.chongbuluo.com/')
    element = browser.find_element(By.XPATH, '//*[@id="welcome"]/a[1]')
    element.click()

    insert_usrname = browser.find_element(By.NAME, 'username')
    insert_usrname.send_keys(usrname)

    insert_usrname = browser.find_element(By.NAME, 'password')
    insert_usrname.send_keys(password)
    insert_usrname.send_keys(Keys.RETURN)  # 模拟键盘
    # 登录
    login = browser.find_element(By.NAME, 'loginsubmit')
    login.click()
    browser.implicitly_wait(30)

    # 判断密码是否正确
    if(confirm(browser)):
        res={"code":400,'msg':'密码错误'}
        return res

    # 点击签到
    browser.find_element(By.XPATH, '//*[@id="thread_types"]/li[15]/a').click()

    # 判断是否签到
    if (loginsuccess(browser)):
        browser.find_element(By.PARTIAL_LINK_TEXT, '今日未签到，点击签到').click()
        browser.implicitly_wait(30)  # 不设置的话 可能没加载  识别不了
        qiandao = browser.find_element(By.XPATH, '//*[@id="wqpc_sign_msg"]/div/p/textarea')
        qiandao.send_keys('今日已签到')
        browser.implicitly_wait(30)
        browser.find_element(By.XPATH, '//*[@id="wqpc_sign_msg"]/div/button').click()
        browser.implicitly_wait(30)
        res = {'code': 200, 'msg': '已签到成功！'}
        return res

    res = {'code': 400, 'msg': '已签到，不要重复签到'}
    print(res)
    return res


def loginsuccess(browser):
    """
    判断是否登录
    已签到1天，明日签到可领1+Bit
    今日未签到，点击签到
    :param browser: 实例化浏览器
    :return:
    """

    msginfo = browser.find_element(By.XPATH, '//*[@id="wp"]/div[2]/div[1]/div[1]/a').text
    print('print:------', msginfo)
    if (msginfo == '今日未签到，点击签到'):
        return True
    else:
        return False


def confirm(brower):
    try:
        text = brower.find_element(By.XPATH, '//*[@id="ntcwin"]/table/tbody/tr/td[2]/div/i').text
        text2 = brower.find_element(By.XPATH, '//*[@id="ntcwin"]/table/tbody/tr/td[2]/div').text
        str = re.findall('登录失败|(密码错误)', text)[0]
        str2 = re.findall('登录失败|(密码错误)', text2)[0]
        print('++++登录失败+++++正则表达提取str：',str)
        print('++++登录失败+++++正则表达提取str2：',str2)
        if (str == '登录失败' or str2 == '密码错误'):
            print('登录失败')
            return True
    except:
        print("登录成功")
        return False


if __name__ == '__main__':
    username = '迷人'
    password = ''
    login_auto(username, password)
